package org.jeecg.modules.pucheng.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.pucheng.bo.EventDetailBo;
import org.jeecg.modules.pucheng.bo.EventListBo;
import org.jeecg.modules.pucheng.bo.EventTypeBo;
import org.jeecg.modules.pucheng.dto.WgApiDto;
import org.jeecg.modules.pucheng.entity.WgEvent;
import org.jeecg.modules.pucheng.service.IWgEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
//@Api(tags = "网格化平台事件接口")
@RestController
@RequestMapping("/pucheng/wgEventApi")
public class WgApiController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IWgEventService wgEventService;

    @ApiOperation("获取token")
    @RequestMapping(value = "/loginSystem", method = RequestMethod.GET)
    public Result<Object> loginSystem() {
        String token = (String) redisUtil.get("access_token");
        if (StringUtils.isBlank(token)){
            //String url = "https://api.beta.aishequ.org/oauth/token";
            String url = "http://59.204.145.208:10027/oauth/token?client_id=2981331767&client_secret=biqyzve4ifaqqc2nw15ezxq9cm9s9utg";
            //String url = "http://172.21.103.6:9460/api/oauth/userAuthorize?client_id=342356&client_secret=credentials-app-secret";
            Map<String, Object> param = new HashMap<>();
            param.put("client_id", "2981331767");
            param.put("client_secret", "biqyzve4ifaqqc2nw15ezxq9cm9s9utg");
            //param.put("loginName", "nphuanght");
            //param.put("loginPwd", "53d88d9c57237f5bc37fadf7faea2376");
            HttpResponse response = HttpRequest.post(url).form(param).execute();
            String resultStr = response.body();
            JSONObject jsonObject = JSONObject.fromObject(resultStr);
            log.info(jsonObject.toString());
            token = jsonObject.getString("access_token");
            String expires_in = jsonObject.getString("expires_in");
            redisUtil.set("access_token", token, Integer.valueOf(expires_in));
        }
        return Result.ok(token);
    }

    //@ApiOperation("事件列表")
    @RequestMapping(value = "/listEvent", method = RequestMethod.GET)
    public Result<Object> listEvent(WgApiDto dto) {
        String token = (String) redisUtil.get("access_token");
        if (StringUtils.isBlank(token)) {
            return Result.error("请获取token");
        }
        dto.setAccess_token(token);
        String url = "http://59.204.145.208:10027/api/listEvent/list";
        Map<String, Object> param = new HashMap<>();
        param = BeanUtil.beanToMap(dto);
        HttpResponse response = HttpRequest.post(url).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8").form(param).execute();
        String resultStr = response.body();
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        List<EventListBo> events = new ArrayList<>();
        log.info(jsonObject.toString());
        if ("1".equals((String) jsonObject.get("code"))) {
            JSONArray array = jsonObject.getJSONArray("rows");
            List<Object> objs = Arrays.asList(array.toArray());
            for (Object o : objs) {
                JSONObject jsonObject1 = (JSONObject) o;
                EventListBo eventVo = (EventListBo) JSONObject.toBean(jsonObject1, EventListBo.class);
                events.add(eventVo);
            }
        } else {
            return Result.error("请求失败");
        }
        return Result.ok(events);
    }

    @ApiOperation("获取所有事件")
    @RequestMapping(value = "/listAllEvent", method = RequestMethod.GET)
    public Result<Object> listAllEvent(WgApiDto dto) {
        String url = "http://59.204.145.208:10027/api/listEvent/getListByType?access_token="+(String) redisUtil.get("access_token");
        Map<String, Object> param = BeanUtil.beanToMap(dto);
        HttpResponse response = HttpRequest.post(url).form(param).execute();
        String resultStr = response.body();

        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        if (jsonObject.getInt("code") == 1) {
            JSONObject json2 = jsonObject.getJSONObject("result");
            int total = json2.getInt("total");
            JSONArray array = json2.getJSONArray("rows");

        }
        return Result.ok();
    }

    //@ApiOperation("获取事件详情")
    @RequestMapping(value = "/listEventDetail", method = RequestMethod.GET)
    public Result<Object> listEventDetail(int type) {
        String eventType = "";
        switch (type) {
            case 1:
                eventType = "todo";  //待办事件
                break;
            case 2:
                eventType = "done";  //经办事件
                break;
            case 3:
                eventType = "history"; //归档事件
                break;
            case 4:
                eventType = "all";  // 辖区事件
                break;
            case 5:
                eventType = "my"; //我发起的
                break;
            default:
                eventType = "";
                break;
        }
        LambdaQueryWrapper<WgEvent> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(eventType)){
            qw.eq(WgEvent::getEventType,eventType);
        }
        List<WgEvent> eventList = wgEventService.list(qw);
        for (WgEvent event:eventList){
            if (event.getUpdateFlag() != null && event.getUpdateFlag() == 2){
                continue;
            }
            try {
                String url = "http://59.204.145.208:10027/api/listEvent/detail?access_token="+(String) redisUtil.get("access_token")+"&eventId="+event.getEventId();
                HttpResponse response = HttpRequest.get(url).execute();
                String resultStr = response.body();
                JSONObject jsonObject = JSONObject.fromObject(resultStr);
                log.info(jsonObject.toString());
                JSONObject object = jsonObject.getJSONObject("result");
                EventDetailBo eventVo = (EventDetailBo) JSONObject.toBean(object, EventDetailBo.class);
                JSONObject json = jsonObject.getJSONObject("attribute");
                JSONObject obj = json.getJSONObject("Map");
                eventVo.setAttribute(obj.toString());
                event.setAttribute(eventVo.getAttribute());
                event.setCode(eventVo.getCode());
                event.setTel(eventVo.getTel());
                event.setContactUser(eventVo.getContactUser());
                event.setSource(eventVo.getSource());
                event.setCollectWay(eventVo.getCollectWay());
                event.setInvolvedNum(eventVo.getInvolvedNum());
                event.setUpdateFlag(2);
                wgEventService.updateById(event);
            } catch (Exception e) {
                continue;
            }
        }
        return Result.ok();
    }


    private Result<List<EventTypeBo>> getReturn(String[] names, String[] types) {
        Result<List<EventTypeBo>> result = new Result<>();
        if (names.length != types.length) {
            result.setSuccess(false);
            result.setMessage("数组不匹配");
            return result;
        }
        List<EventTypeBo> list = new ArrayList<>();
        for (int i = 0; i < names.length; i++) {
            EventTypeBo bo = new EventTypeBo();
            bo.setName(names[i]);
            bo.setType(types[i]);
            list.add(bo);
        }
        result.setCode(200);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    //@ApiOperation("事件类型_>获取所有事件类型名称及对应的type  事件类型【A001093199】 ")
    @RequestMapping(value = "/getAllType", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getAllType() {
        String[] names = {"环保", "水", "禁养区生猪养殖回潮", "限养区规模化生猪养殖污水排放", "黑臭水体", "水源地周边违法生产经营活动",
                "企业外围偷排废水", "其它", "气", "工地扬尘", "露天烧烤", "焚烧垃圾",
                "烟囱冒黑烟", "机动车冒黑烟", "餐饮油烟污染", "道路扬尘", "其它", "声",
                "工业企业生产噪声", "建筑施工噪声", "营业性文化娱乐场所的边界噪声", "商业经营活动使用空调器、冷却塔产生环境 噪声", "其它", "渣",
                "乱丢弃废油桶涂料桶", "乱丢弃医疗垃圾", "其它", "其它"};
        String[] types = {"31", "3103", "310306", "310307", "310308", "310309",
                "310310", "310304", "3105", "310501", "310508", "310503",
                "310509", "310510", "310502", "310511", "310506", "3104",
                "310405", "310403", "310402", "310401", "310404", "3106",
                "310601", "310602", "310699", "3199"};
        return getReturn(names, types);
    }

    //@ApiOperation("影响范围>获取所有影响范围名称及对应的type   影响范围【A001093094】 ")
    @RequestMapping(value = "/getInfluenceDegree", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getInfluenceDegree() {
        String[] names = {"小", "中", "大", "重大"};
        String[] types = {"01", "02", "03", "04"};
        return getReturn(names, types);
    }


    //@ApiOperation("信息来源>获取所有信息来源名称及对应的type   信息来源【A001093222】 ")
    @RequestMapping(value = "/getSource", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getSource() {
        String[] names = {"目击", "举报", "微博", "QQ", "留言板", "短信", "热线", "应急指挥中心", "微信", "上报", "网站群", "来访", "来信"};
        String[] types = {"01", "02", "03", "04", "05", "06", "07", "10", "09", "11", "12", "21", "22"};
        return getReturn(names, types);
    }

    //@ApiOperation("紧急程度>获取所有紧急程度名称及对应的type    紧急程度【A001093271】 ")
    @RequestMapping(value = "/getUrgencyDegree", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getUrgencyDegree() {
        String[] names = {"一般", "紧急", "加急"};
        String[] types = {"01", "02", "03"};
        return getReturn(names, types);
    }

    //@ApiOperation("涉及人数>获取所有涉及人数名称及对应的type   涉及人数【A001093270】 ")
    @RequestMapping(value = "/getInvolvedNum", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getInvolvedNum() {
        String[] names = {"无", "1 人", "2 人", "3-4 人", "5-10 人", "10-30 人"};
        String[] types = {"00", "01", "02", "03", "04", "05"};
        return getReturn(names, types);
    }

    //@ApiOperation("采集渠道>获取所有采集渠道名称及对应的type     采集渠道【A001093096】 ")
    @RequestMapping(value = "/getCollectWay", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getCollectWay() {
        String[] names = {"手机", "PC", "呼叫中心", "网站群", "微信"};
        String[] types = {"01", "02", "03", "04", "05"};
        return getReturn(names, types);
    }

    //@ApiOperation("附件标记>获取所有附件标记名称及对应的type    附件标记【B063】 ")
    @RequestMapping(value = "/getAttrFlag", method = RequestMethod.GET)
    public Result<List<EventTypeBo>> getAttrFlag() {
        String[] names = {"无", "图片", "音频", "视频"};
        String[] types = {"0", "1", "2", "3"};
        return getReturn(names, types);
    }

}
